package fun.sanguo.service.interact.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import fun.sanguo.mapper.interact.InteractPersonageViewMapper;
import fun.sanguo.model.dto.PageInsert;
import fun.sanguo.model.dto.interact.InteractPersonageViewInsert;
import fun.sanguo.model.entity.interact.InteractPersonageViewEntity;
import fun.sanguo.model.enums.ResEnums;
import fun.sanguo.service.interact.InteractPersonageViewService;
import fun.sanguo.utils.DateUtils;
import fun.sanguo.utils.IdUtils;
import fun.sanguo.utils.exception.ArtificialException;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 互动-人物浏览记录 Service实现类
 *
 * @author ZYP
 * @date 2023-10-13
 */
@Service
public class InteractPersonageViewServiceImpl implements InteractPersonageViewService {

    @Resource
    private InteractPersonageViewMapper interactPersonageViewMapper;

    /**
     * 新增
     *
     * @param pageInsert
     * @param userId
     * @param userIp
     * @return
     * @throws ArtificialException
     */
    @Override
    public boolean insert(PageInsert<InteractPersonageViewInsert> pageInsert, String userId, String userIp) throws ArtificialException {
        // 新增参数
        InteractPersonageViewEntity interactPersonageViewEntity = new InteractPersonageViewEntity();
        // 转换新增参数
        try {
            // 接收参数
            InteractPersonageViewInsert interactPersonageViewInsert = new ObjectMapper().convertValue(pageInsert.getParam(), InteractPersonageViewInsert.class);
            // 赋值到实体类
            BeanUtils.copyProperties(interactPersonageViewInsert, interactPersonageViewEntity);
            interactPersonageViewEntity.setUserId(userId);
            interactPersonageViewEntity.setUserIp(userIp);
            interactPersonageViewEntity.setViewTime(new Date());
            // 其他参数赋值
            interactPersonageViewEntity.setId(String.valueOf(new IdUtils().nextId()));
            interactPersonageViewEntity.setCreateBy("system");
            interactPersonageViewEntity.setCreateTime(DateUtils.getTime(DateUtils.DATE_FORMAT_11));
            interactPersonageViewEntity.setUpdateBy("system");
            interactPersonageViewEntity.setUpdateTime(DateUtils.getTime(DateUtils.DATE_FORMAT_11));
            interactPersonageViewEntity.setVersion(1);
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_PARAM.getCode(), ResEnums.ERR_PARAM.getMsg(), e);
        }
        // 新增数据并得到操作结果
        try {
            // 新增
            int amount = interactPersonageViewMapper.insert(interactPersonageViewEntity);
            // 返回操作结果
            return amount > 0;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }
}
